package com.zxcl.controller;

import com.alibaba.fastjson2.JSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AliPayBackController {

  /**
   * 给支付宝进行回调的接口
   * http://localhost:8888/callBack
   * 校验：这个接口只能是支付宝来调用用，不能让其它人使用HTTP工具来调用
   */
  @RequestMapping("callBack")
  public void callBack(HttpServletRequest request){
//    Map<String, String[]> parameterMap = request.getParameterMap();
//    Enumeration<String> parameterNames = request.getParameterNames();
//    String json= JSON.toJSONString(parameterMap);
    Map<String, String> parameterMap = getParameterMap(request);
    String json = JSON.toJSONString(parameterMap);
    String trade_status = parameterMap.get("trade_status");
    if(trade_status.equals("TRADE_SUCCESS")){
      System.out.println("用户支付成功");
      //更新自己系统的订单状态
    }else{
      System.out.println("支付失败");
    }
    System.out.println(json);
  }
  /**
   * 获取request中的参数集合转Map
   * Map<String,String> parameterMap = RequestUtil.getParameterMap(request)
   * @param request
   * @return
   */
  public Map<String, String> getParameterMap(HttpServletRequest request) {
    Map<String, String> map = new HashMap<>();
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
      String paramName = paramNames.nextElement();
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() != 0) {
          map.put(paramName, paramValue);
        }
      }
    }
    return map;
  }
}
